import re
import globals
from SendToNeighbours import send_message_to_neighbors
from WaitMessages import wait_till_neighbors_reply
import configfile
import GetDataFromAuthServer

def get_and_reply_messages (mp, msg):

    try :
        globals.globalGetMessageRequestsLock.acquire()
        globalGetMessageRequests = globals.globalGetMessageRequests + 1
    finally :
        globals.globalGetMessageRequestsLock.release()

    temp=msg.data.split(',')
    user = temp[0]
    userGroup=temp[1]
    #print 'In get and reply messages user ' + user

    returnMessageList = []

    try :
        globals.globalCacheMessageListLock.acquire()
        for item in globals.globalCacheMessageList :
            #print item
            if ',' in item.toUserName :
                receivers = item.toUserName.split(',')
                for i in receivers :
                    if (i == user) :
                        returnMessageList.append(item)

            elif item.toUserName == user :
                returnMessageList.append(item)
            elif item.toUserName == userGroup :
                if user not in item.groupList :
                    item.groupList.append(user)
                    returnMessageList.append(item)

    except KeyError :
        print 'No such user'
    finally:
        globals.globalCacheMessageListLock.release()

    #print "In get and reply message returnMessageList is "
    print returnMessageList
    # broadcast a message to get messages from other nodes
    temp = msg.clone()
    failedSending = send_message_to_neighbors (mp, temp)
    # Destinations that this thread has to wait for
    #mapS = mp.ConfigurationMap[mp.thisName]
    listDest = []
    for item in configfile.get_node_neighbors(mp.thisName) :
        if not item == mp.thisName :
            if not item == msg.src:
                if item not in failedSending :
                    listDest.append(item)

    # print 'Waiting for neighbors : ',
    # print listDest
    returnMessageList = wait_till_neighbors_reply(listDest, user, returnMessageList)

    print "After wait list is :",
    print returnMessageList

    try :
        globals.globalGetMessageRequestsLock.acquire()
        globalGetMessageRequests = globalGetMessageRequests - 1
    finally :
        globals.globalGetMessageRequestsLock.release()

    if returnMessageList == False :
        if globalGetMessageRequests == 0 :
            try :
                globals.globalShutdownLock.acquire()
                globals.globalShutdown = False
            finally :
                globals.globalShutdownLock.release()
        return False

    return returnMessageList
